package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.springboot.controller.dto.LoginDTO;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.controller.request.LoginRequest;
import com.example.springboot.entity.User;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.IUserService;
import com.example.springboot.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
//使用指定类初始化日志对象，在日志输出的时候，可以打印出日志信息所在的类
@Slf4j
@Service
//@Service注解将UserService转为spring的一个组件
public class UserService implements IUserService {

    @Autowired //通过autowired导入userMapper
    UserMapper userMapper;

//    添加默认密码和加密符文
    private static final String DEFAULT_PASS="123";
    private static final String PASS_SALT="sixia";
    private static final Integer DEFAULT_MONEY=0;

    @Override
    public List<User> list() {
//        有时需要try catch处理来解决函数存在的问题
        return userMapper.list();
    }

    @Override
    public PageInfo<User> page(BaseRequest baseRequest){
//        dependency引入pagehelper
//        PageHelper传入页面和每页信息条数
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<User> users=userMapper.listByCondition(baseRequest);
        return new PageInfo<>(users);
    }

    @Override
    public void save(User user){//        当做卡号来处理
        Date date= new Date();
//     通过hashCode编码将fastSimpleUUID产生的字母和数字转为数字
        user.setNickName(DateUtil.format(date,"yyyyMMdd")+Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        if(StrUtil.isBlank(user.getPassword())){
            user.setPassword(DEFAULT_PASS);
        }
        if(user.getMoney()==null){
            user.setMoney(DEFAULT_MONEY);
        }
        user.setPassword(securePass(user.getPassword()));//设置md5加密
        try{
            userMapper.save(user);
        }catch(DuplicateKeyException e){
            log.error("数据插入失败,nickName:{}",user.getNickName());
            throw new ServiceException("用户插入失败");
        }
    }

//    用户注册
    @Override
    public void register(User user){//        当做卡号来处理
        Date date= new Date();
//     通过hashCode编码将fastSimpleUUID产生的字母和数字转为数字
        user.setNickName(DateUtil.format(date,"yyyyMMdd")+Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        if(StrUtil.isBlank(user.getPassword())){
            user.setPassword(DEFAULT_PASS);
        }
        user.setMoney(DEFAULT_MONEY);
        user.setPassword(securePass(user.getPassword()));//设置md5加密
        try{
            userMapper.register(user);
        }catch(DuplicateKeyException e){
            log.error("用户注册失败,nickName:{}",user.getNickName());
            throw new ServiceException("用户注册失败");
        }
    }


    //  通用代码封装 md5加密
    private String securePass(String password){
        return SecureUtil.md5(password+PASS_SALT);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(new Date());
        userMapper.updateById(user);

    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }


    @Override
    public LoginDTO login(LoginRequest request) {

        User user = null;
        System.out.println(request.getUserName());
        try{
            user = userMapper.getByUserName(request.getUserName());
        }catch(Exception e){
            log.error("根据用户名{}查询出错",request.getUserName());
            throw new ServiceException("用户名出错");
        }
//        User user=userMapper.getByUserNameAndPassword(request.getUsername(),request.getPassword());
        if(user == null){
//            业务层应当返回一个业务对象,而非结果对象? 这句话咋理解
            throw new ServiceException("用户名或密码错误");
        }
//        判断密码是否合法
        String securePass = securePass(request.getPassword());
        if(!securePass.equals(user.getPassword())){
            throw new ServiceException("密码错误");
        }
        LoginDTO loginDTO=new LoginDTO();
        BeanUtils.copyProperties(user,loginDTO);//把user的属性赋值到loginDTO中去

//        生成token
        String token = TokenUtils.genToken(String.valueOf(user.getId()), user.getPassword());
        loginDTO.setToken(token);
        return loginDTO;
    }

    @Override
    public void handleAccount(User user) {
        System.out.println(user);
        Integer score = user.getScore();
        if(score == null){
            return ;
        }
        Integer id = user.getId();
        User dbUser = userMapper.getById(id);
        dbUser.setMoney(dbUser.getMoney() + score);
        System.out.println("用户金额为"+dbUser.getMoney());
        userMapper.updateById(dbUser);
    }

}
